﻿using AllSqlHelperWin.SQLHelperForms.MysqlForms;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using MySql.Data.MySqlClient;
using Org.BouncyCastle.Crypto;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Util.NoSQLHelpers;
using static System.Net.WebRequestMethods;

namespace AllSqlHelperWin.NoSQLHelperForms.MongoDBForms
{
    public partial class MongoDBHelperForm : Form
    {
        #region 变量
        /// <summary>
        /// 
        /// </summary>
        private string mongoDBConStr = ConfigurationSettings.AppSettings["MongoDBConStr"].Trim();
        private string mongoDBName = ConfigurationSettings.AppSettings["MongoDBName"].Trim();

        /// <summary>
        /// DB
        /// </summary>
        IMongoDatabase _mongoDatabase;
        #endregion

        public MongoDBHelperForm()
        {
            InitializeComponent();
        }

        private void MysqlHelperForm_Load(object sender, EventArgs e)
        {
            try
            {
                cmbClass.SelectedIndex = 0;
                dtTStart.Text = DateTime.Now.AddDays(-30).ToString();
                dtTEnd.Text = DateTime.Now.AddDays(1).ToString();

                _mongoDatabase = MongoDBHelper.Initial(mongoDBConStr, mongoDBName);  // 
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化页面报错！错误信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                #region 
                string name = txtName.Text.Trim();
                bool isGender_Boy = rdBtnGenderB.Checked;
                string userClass = cmbClass.Text.Trim();
                string dtStart = dtTStart.Text.Trim();
                string dtEnd = dtTEnd.Text.Trim();

                // 执行
                var list = _mongoDatabase.GetCollection<UserModel_MongoDB>("User");
                var result = list.AsQueryable().Where(p => p.Gender == isGender_Boy
                    && ((string.IsNullOrEmpty(userClass) || userClass.Equals("全部")) ? 1 == 1 : p.Class == userClass) && p.CreateTime >= Convert.ToDateTime(dtStart)
                    && p.CreateTime <= Convert.ToDateTime(dtEnd)).ToList();

                if (!string.IsNullOrEmpty(name))
                {
                    result = result.Where(p => p.Name == name).ToList();
                }

                #endregion

                if (result != null && result.Count > 0)
                {
                    dataGridView1.DataSource = result;
                }
                else
                {
                    dataGridView1.DataSource = new DataTable().DefaultView;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询信息失败！错误信息：" + ex.Message);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                #region 
                string name = txtName.Text.Trim();
                bool isGender_Boy = rdBtnGenderB.Checked;
                string userClass = cmbClass.Text.Trim();
                string dtStart = dtTStart.Text.Trim();
                string dtEnd = dtTEnd.Text.Trim();

                // 执行
                var list = _mongoDatabase.GetCollection<UserModel_MongoDB>("User");

                var result = list.Find(p => p.Gender == isGender_Boy
                    && ((string.IsNullOrEmpty(userClass) || userClass.Equals("全部")) ? 1 == 1 : p.Class == userClass) && p.CreateTime >= Convert.ToDateTime(dtStart)
                    && p.CreateTime <= Convert.ToDateTime(dtEnd)).Limit(80).Skip(0).ToList();
                if (!string.IsNullOrEmpty(name))
                {
                    result = result.Where(p => p.Name == name).ToList();
                }

                #endregion

                if (result != null)
                {
                    dataGridView1.DataSource = result;
                }
                else
                {
                    dataGridView1.DataSource = new DataTable().DefaultView;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询信息失败！错误信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 添加
        /// </summary>
        private void 添加ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MongoDBAddForm mysqlAddForm = new MongoDBAddForm();
            mysqlAddForm.ShowDialog();
        }

        /// <summary>
        /// 更新
        /// </summary>
        private void 更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                //判断是否选中单元格
                if (dataGridView1.SelectedRows.Count > 0)//有选中
                {
                    UserModel_MongoDB userModel = new UserModel_MongoDB();
                    userModel._id = ObjectId.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
                    userModel.Name = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
                    userModel.Class = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
                    userModel.Age = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[3].Value);
                    string genderStr = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
                    userModel.Gender = genderStr == "男" ? true : false;
                    userModel.CreateTime = Convert.ToDateTime(dataGridView1.SelectedRows[0].Cells[5].Value);

                    MongoDBUpdateForm mysqlUpdateForm = new MongoDBUpdateForm(userModel);
                    mysqlUpdateForm.ShowDialog();
                }
                else
                {
                    MessageBox.Show("请选择任意一行！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("更新行出错！错误信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                //判断是否选中单元格
                if (dataGridView1.SelectedRows.Count > 0)//有选中
                {
                    List<int> ids = new List<int>();

                    string idStr = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
                    ObjectId id = ObjectId.Parse(idStr);

                    var collection = MongoDBHelper.GetCollection<UserModel_MongoDB>("User");
                    MongoDBHelper.DeleteOne(collection, Builders<UserModel_MongoDB>.Filter.Eq("_id", id));
                    MessageBox.Show("删除行成功！");
                }
                else
                {
                    MessageBox.Show("请选择任意一行！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除行出错！错误信息：" + ex.Message);
            }
        }

        private void 删除删除全部ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var collection = MongoDBHelper.GetCollection<UserModel_MongoDB>("User");
                MongoDBHelper.DeleteAll(collection);
                MessageBox.Show("删除全部行成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除全部行出错！错误信息：" + ex.Message);
            }
        }

        private void 删除批量删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string nameStr = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();

                var collection = MongoDBHelper.GetCollection<UserModel_MongoDB>("User");
                MongoDBHelper.DeleteBatch(collection, Builders<UserModel_MongoDB>.Filter.In("Name", new string[] { nameStr }));

                MessageBox.Show("批量删除行成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("批量删除行出错！错误信息：" + ex.Message);
            }
        }
    }
}